package com.aliyun.heiyu.powermaster.server.rotary.task;

import com.aliyun.heiyu.common.util.HttpUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.powermaster.server.rbac.object.dto.OutDTO;
import com.aliyun.heiyu.powermaster.server.rbac.service.impl.TokenManagerImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description 用户退出定时器
 * @Author shun.zhang
 * @Date 2021/1/10 15:44
 **/
public class UserOutTask implements Job {
    private String outUrl = PropertiesUtil.getValue("userConfig.properties", "outUrl");
    private static Logger logger = LoggerFactory.getLogger(UserOutTask.class);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(16, 16, 200, TimeUnit.MILLISECONDS,
        new ArrayBlockingQueue<Runnable>(100));
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("执行用户退出定时器");
        Map<String, OutDTO> userList = TokenManagerImpl.userList;
        if (null == userList) {
            return;
        }
        for (Map.Entry<String, OutDTO> out : userList.entrySet()) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    OutDTO outDTO = out.getValue();
                    if (System.currentTimeMillis() - outDTO.getOutTime() > 20000) {
                        logger.info("准备执行退出命令:"+outDTO);
                        StringBuilder url = new StringBuilder();
                        url.append(outUrl)
                            .append("?iscUserId=").append(outDTO.getIscUserId())
                            .append("&service=").append(outDTO.getService())
                            .append("&token=").append(outDTO.getToken())
                            .append("&username=").append(outDTO.getUsername());
                        String iscOutUrl = url.toString();
                        logger.info("执行退出命令:"+iscOutUrl);
                        HttpUtil.getHttpsRequest(iscOutUrl);
                        TokenManagerImpl.userList.remove(outDTO.getUsername());
                    }
                }
            });

        }

    }
}
